#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    // 设置根节点
    ui->treeWidget->setHeaderLabel("动物");

    // 添加顶层节点
    QTreeWidgetItem* item1 = new QTreeWidgetItem();
    item1->setText(0, "猫");
    ui->treeWidget->addTopLevelItem(item1);

    QTreeWidgetItem* item2 = new QTreeWidgetItem();
    item2->setText(0, "狗");
    ui->treeWidget->addTopLevelItem(item2);

    QTreeWidgetItem* item3 = new QTreeWidgetItem();
    item3->setText(0, "鸟");
    ui->treeWidget->addTopLevelItem(item3);

    // 添加子节点
    QTreeWidgetItem* item4 = new QTreeWidgetItem();
    item4->setText(0, "田园猫");
    item1->addChild(item4);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    const QString& text = ui->lineEdit->text();
    if (text.isEmpty())
    {
        return;
    }
    // 添加到顶层节点中
    QTreeWidgetItem* item = new QTreeWidgetItem();
    item->setText(0, text);
    ui->treeWidget->addTopLevelItem(item);
}

void Widget::on_pushButton_2_clicked()
{
    const QString& text = ui->lineEdit->text();
    if (text.isEmpty())
    {
        return;
    }
    QTreeWidgetItem* item = new QTreeWidgetItem();
    item->setText(0, text);
    // 获取到当前选中的节点
    QTreeWidgetItem* current = ui->treeWidget->currentItem();
    if (current == nullptr)
    {
        return;
    }
    // 插入到子节点
    current->addChild(item);

}

void Widget::on_pushButton_3_clicked()
{
    // 获取选中节点
    QTreeWidgetItem* cur = ui->treeWidget->currentItem();
    if (cur == nullptr)
    {
        return;
    }
    // 获取当前节点父节点
    QTreeWidgetItem* parent = cur->parent();
    if (parent == nullptr)
    {
        // 顶层节点
        int index = ui->treeWidget->indexOfTopLevelItem(cur);
        ui->treeWidget->takeTopLevelItem(index);
    }
    else
    {
        // 非顶层
        parent->removeChild(cur);
    }
}
